package com.itheima.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.itheima.excel.StudentListener;
import com.itheima.excel.model.StudentModel;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Result;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.StudentService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Positive;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.controller
 */
@RestController
@Slf4j
@AllArgsConstructor
@RequestMapping("/students")
@Valid
public class StudentController {

    private StudentService studentService;

    @GetMapping
    public Result pageQuery(StudentQueryParam studentQueryParam){
        PageResult<Student> pageResult = studentService.pageQuery(studentQueryParam);
        return Result.success(pageResult);
    }

    @PostMapping
    public Result add(@Valid @RequestBody Student student){
        studentService.add(student);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        return Result.success(studentService.getById(id));
    }

    @PutMapping
    public Result update(@RequestBody Student student){
        studentService.updateById(student);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id){
        studentService.deleteById(id);
        return Result.success();
    }

    @PutMapping("/violation/{id}/{score}")
    public Result violation(@PathVariable Integer id, @Positive(message = "分数不能为空或负数") @PathVariable Integer score){
        studentService.violation(id,score);
        return Result.success();
    }

    /**
     * 批量导入学员信息
     * @param clazzId
     * @param file
     * @return
     */
    @PostMapping("/import/{clazzId}")
    public Result doImport(@PathVariable Integer clazzId, MultipartFile file) throws IOException {
        //解析excel，调用业务批量保存
        // 构建excel文件读取监听器
        StudentListener listener = new StudentListener(new ArrayList<>());
        // 读取excel内容
        EasyExcel.read(file.getInputStream(), StudentModel.class, listener).sheet().doRead();
        // 获取读取的结果
        List<StudentModel> stuList = listener.getStuList();
        // 批量导入
        studentService.importStudent(stuList, clazzId);
        return Result.success();
    }

    /**
     * 导出学员信息
     * @param queryParam
     * @param response 只要是下载文件，一定会用到response，且方法返回类型void
     */
    /*@GetMapping("/export")
    public void export(StudentQueryParam queryParam, HttpServletResponse response) throws IOException {
        // 调用业务层查询符合条件的学员列表
        List<StudentModel> studentModelList = studentService.list(queryParam);
        // 导出excel
        // 单元格的格式化
        WriteCellStyle writeCellStyle = new WriteCellStyle();
        // 样式水平居中
        writeCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 修改下载文件的名称
        response.reset();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=abc.xlsx");


        try (
            // 使用EasyExcel写入数据到输出流
            ByteArrayOutputStream out = new ByteArrayOutputStream()
        ) {
            EasyExcel.write(out)

                .head(StudentModel.class)
                .registerWriteHandler(new HorizontalCellStyleStrategy(null, writeCellStyle))
                .sheet("XXX")
                .doWrite(studentModelList);

            response.setContentLength(out.size());
            out.writeTo(response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
        }
    }*/

    @GetMapping("/export")
    public void export(StudentQueryParam queryParam, HttpServletResponse response) throws IOException {
        // 调用业务层查询符合条件的学员列表
        List<StudentModel> studentModelList = studentService.list(queryParam);
        // 设置响应内容类型
        response.setContentType("application/x-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String("abc.xls".getBytes(), "ISO-8859-1"));


        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            // 使用EasyExcel写入数据到输出流
            EasyExcel.write(out)
                .sheet("Sheet1")
                .doWrite(studentModelList);

            // 设置响应体大小
            response.setContentLength(out.size());
            // 写入响应流并刷新
            out.writeTo(response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
        }
    }

    @GetMapping("/export2")
    public void export2(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=abc.txt");
        ByteArrayInputStream is = new ByteArrayInputStream("abc".getBytes());
        ///response.getOutputStream().write();
    }
}
